package com.java.base.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class NIOSocket {
    static Logger logger = Logger.getLogger(NIOSocket.class.getSimpleName());

    static {
        logger.setLevel(Level.INFO);
    }


    public static void client(int port) throws IOException, InterruptedException {

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("127.0.0.1", port));
        socketChannel.configureBlocking(false);
        socketChannel.setOption(StandardSocketOptions.TCP_NODELAY, true);

        if (socketChannel.isConnectionPending()) {
            while (!socketChannel.finishConnect()) {
                logger.warning("finishConnect can't be finish");
                Thread.sleep(1000);
            }
            logger.warning("Connect can be finish");
        }

        new Thread(() -> {
            try {
                send(socketChannel);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while (socketChannel.isOpen()) {
            byteBuffer.clear();
            int i = socketChannel.read(byteBuffer);
            if (i <= 0) {
                Thread.sleep(1000);
                continue;
            }
            logger.info("收到：" + new String(byteBuffer.array(), 0, i));
        }


    }

    public static void send(SocketChannel socketChannel) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        Scanner scanner = new Scanner(System.in);
        logger.info("输入：");
        while (socketChannel.isOpen()) {
            String s = scanner.nextLine();
            if (s.equals("stop")) {
                logger.info("结束程序");
                socketChannel.close();
                break;
            }
            byteBuffer.clear();
            byteBuffer.put(s.getBytes(StandardCharsets.UTF_8));
            byteBuffer.flip();
            socketChannel.write(byteBuffer);
        }
    }


    public static void read(SocketChannel socketChannel) throws IOException, InterruptedException {
        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_READ);

        int keyNum;
        while (socketChannel.isOpen()) {
            keyNum = selector.select();
            logger.info("Already Read Num:" + keyNum);
            if (keyNum == 0) {
                Thread.sleep(2000);
                continue;
            }


        }


    }

    public static void main(String[] args) throws IOException, InterruptedException {
        client(0xbbbb);
    }


}
